using Godot;
using Microsoft.VisualBasic;
using System;
using System.Reflection;

[Tool]
public partial class Board : Node2D
{
	public const float FRAME_SIZE = 2;
	public const float LINE_SIZE = 1;

    private float _unitSize;
	[Export]
	public float UnitSize
	{
		get => _unitSize;
		set
		{
			_unitSize = value;
			QueueRedraw();
		}
	}

	private Color _color;
	[Export]
	public Color LineColor
	{
		get => _color;
		set
		{
			_color = value;
			QueueRedraw();
		}
	}
	public Vector2 FrameSize => new(UnitSize * Rule.BOARD_WIDTH, UnitSize * Rule.BOARD_HEIGHT);
	public Vector2 FramePos => -0.5f * FrameSize;

	public delegate void GridClick(int x, int y);
	public GridClick OnGridClick { get; set; }

    public override void _Input(InputEvent e)
    {
        if (e is InputEventMouseButton mbe && mbe.Pressed && mbe.ButtonIndex == MouseButton.Left)
		{
			var grid = (Vector2I)((GetGlobalMousePosition() / UnitSize) + 0.5f * new Vector2(Rule.BOARD_WIDTH + 1, Rule.BOARD_HEIGHT + 1)).Floor();
			OnGridClick(grid.X, grid.Y);
		}
    }
	public Vector2 GetGridPosition(int gridX, int gridY) => UnitSize * new Vector2(gridX - 0.5f * Rule.BOARD_WIDTH, gridY - 0.5f * Rule.BOARD_HEIGHT);
	public Vector2 GetGlobalPosition(int gridX, int gridY) => GlobalPosition + GetGridPosition(gridX, gridY);

    public override void _Draw()
    {
		var frameSize = FrameSize;
		var framePos = FramePos;
		
		for (var i = 0; i < Rule.BOARD_HEIGHT; i++)
		{
			var h = i * UnitSize;
			DrawLine(framePos + new Vector2(0, h), framePos + new Vector2(frameSize.X, h), LineColor, LINE_SIZE);
		}

		var vLen = Rule.BOARD_SIDE_LEN * UnitSize;
		for (var i = 0; i < Rule.BOARD_WIDTH; i++)
		{
			var v = i * UnitSize;
			DrawLine(framePos + new Vector2(v, 0), framePos + new Vector2(v, vLen), LineColor, LINE_SIZE);
			DrawLine(framePos + new Vector2(v, frameSize.Y), framePos + new Vector2(v, frameSize.Y - vLen), LineColor, LINE_SIZE);
		}

		DrawLine(framePos + new Vector2(3 * UnitSize, 0), framePos + new Vector2(5 * UnitSize, 2 * UnitSize), LineColor, LINE_SIZE);
		DrawLine(framePos + new Vector2(5 * UnitSize, 0), framePos + new Vector2(3 * UnitSize, 2 * UnitSize), LineColor, LINE_SIZE);

		DrawLine(framePos + new Vector2(3 * UnitSize, Rule.BOARD_HEIGHT * UnitSize), framePos + new Vector2(5 * UnitSize, (Rule.BOARD_HEIGHT - 2) * UnitSize), LineColor, LINE_SIZE);
		DrawLine(framePos + new Vector2(5 * UnitSize, Rule.BOARD_HEIGHT * UnitSize), framePos + new Vector2(3 * UnitSize, (Rule.BOARD_HEIGHT - 2) * UnitSize), LineColor, LINE_SIZE);

		var frame = new Rect2(framePos, frameSize);

		DrawRect(frame, LineColor, false, FRAME_SIZE);
    }
}
